#!/usr/bin/env node
// const log = console.log;

// let argv = process.argv;

// log("argv length:", argv.length);
// log("argv:", argv);

// const expression = process.argv[2];
// console.log(expression + "=%d", eval(expression));


// log(process.argv[0]);
// log(process.argv[1]);
// log(process.argv[2]);

// 检查命令行参数
const args = process.argv.slice(2); // 获取命令行参数，去掉前两个默认参数

// 使用说明
const usage = 'Usage: node 02-calc.js <expression>';
const helpText = `${usage}\nExample: node 02-calc.js 2+2*2`;

// 检查是否有参数或参数是 --help 或 -h
if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
  console.log(helpText);
  process.exit(0);
}

// 检查参数数量是否过多
if (args.length > 3) {
  console.log('Too many arguments. Only the first three will be considered.');
  args = args.slice(0, 3);
}

// 将命令行参数合并为一个表达式字符串
const expression = args.join(' ');

try {
  // 使用 Function 构造函数来计算表达式
  const result = Function('"use strict"; return (' + expression + ')')();
  console.log('Result:', result);
} catch (error) {
  // 如果表达式不合法，打印错误信息
  console.error('Error: Invalid mathematical expression.');
}